#include "operar.h"

void usage(const char *program, Error error_code)
{
    fprintf(stderr, "Usage: %s <num1> <num2>\n", program);
    const char *error_mesg;
    switch (error_code)
    {
        case ERR_ARGS:
            error_mesg = "wrong number of arguments";
            break;
        case ERR_NUMBER:
            error_mesg = "one of the arguments is not a number";
            break;
        case ERR_OPERATOR:
            error_mesg = "the operator cannot be recognised";
        default:
            break;
    }
    fprintf(stderr, "ERROR: %s\n", error_mesg);
}

Error correct_args(int argc, char **argv)
{
    if(argc != 4)
        return ERR_ARGS;
    for(int i = 1; i < argc; ++i)
        if(i == 2){
            int ret = check_operator(argv[i]);
            if(ret)
                return ret;
        } else {
            for(char *p = argv[i]; *p; ++p)
                if(*p < '0' || *p > '9')
                    return ERR_NUMBER;
        }
    return ERR_OK;
}

Error check_operator(char *op)
{
    if(*(op + 1))        //More than one character
        return ERR_OPERATOR;
    switch (op[0])
    {
        case '+':
        case '-':
        case '*':
        case '/':
        case '%':
            return 0;
        default:
            return ERR_OPERATOR;
    }
}

void operate(int *result_var, int a, int b, char op)
{
    switch (op)
    {
        case '+':
            *result_var = a + b;
            return;
        case '-':
            *result_var = a - b;
            return;
        case '*':
            *result_var = a * b;
            return;
        case '/':
            *result_var = a / b;
            return;
        case '%':
            *result_var = a % b;
            return;
        default:
            assert(0 && "operate: unreachable");
    }
}
